﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using AAA.Meta.Command;
using Newtonsoft.Json;
using System.Reflection;
using AAA.Command.WCF;

namespace AAA.Communication.WCFService
{
    // NOTE: If you change the class name "GameService" here, you must also update the reference to "GameService" in App.config.
    public class CommandService : ICommandService
    {
        public string ExecuteCommand(string strData)
        {            
            CommandProfile commandProfile  = JsonConvert.DeserializeObject<CommandProfile>(strData);;
            string[] strCommand;
            Assembly asmb;
            ICommand command;
            int iReturnCode;

            try
            {
                strCommand = CommandConfig.Config().GetCommand(commandProfile.Command);

                if (strCommand.Length != 2)
                {
                    commandProfile.ReturnCode = "1001";
                    commandProfile.ReturnMessage = "Can't find the command : " + commandProfile.Command;
                    return JsonConvert.SerializeObject(commandProfile, Formatting.Indented);
                }

                asmb = Assembly.LoadFrom(strCommand[0]);
                command = (ICommand)asmb.CreateInstance(strCommand[1]);
                if (command == null)
                {
                    commandProfile.ReturnCode = "1002";
                    commandProfile.ReturnMessage = "Can't create command : " + commandProfile.Command + "," + strCommand[0] + "," + strCommand[1];
                    return JsonConvert.SerializeObject(commandProfile, Formatting.Indented);
                }

                iReturnCode = command.Execute(commandProfile.Data);

                commandProfile.ReturnCode = iReturnCode.ToString();
                commandProfile.ReturnMessage = ReturnCode.Config().GetMessage(iReturnCode.ToString());
            }
            catch (Exception ex)
            {
                commandProfile.ReturnCode = "1003";
                commandProfile.ReturnMessage = ex.Message + "," + ex.StackTrace;
            }
            finally
            {
            }
            return JsonConvert.SerializeObject(commandProfile, Formatting.Indented);
        }
    }
}
